package com.atom.common.remote.xt.dao;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.Column;

import org.springframework.stereotype.Repository;

import com.atom.common.dao.AvensCommonDao;
import com.atom.common.exception.AvensRemoteDatabaseDaoException;
import com.atom.common.remote.xt.XtUpdateDataDO;
import com.atom.common.util.DateUtil;

@Repository
public class XtUpdateDataDao extends AvensCommonDao<XtUpdateDataDO> {

  public void insert(Object old, Object update, Integer id, String tableName) {
    Class<? extends Object> clazz = old.getClass();
    Field[] fields = clazz.getDeclaredFields();
    List<Field> result = new ArrayList<Field>();
    for (Field field : fields){
      if(field.getAnnotation(Column.class) != null)
        result.add(field);
    }

    for(Field field : result){
      System.out.println("被注解的字段为:" + field.getName());
      try {
        PropertyDescriptor pd = new PropertyDescriptor(field.getName(),clazz);
        Method getMethod = pd.getReadMethod();
        String oldValue = getStringValue(getMethod.invoke(old), field);
        String newValue = getStringValue(getMethod.invoke(update), field);        
        Column annotation = field.getAnnotation(Column.class);
        String name = annotation.name();
        XtUpdateDataDO entity = new XtUpdateDataDO();
        entity.setJiLuBiao(id);
        entity.setXiuGaiBiao(tableName);
        entity.setXiuGaiZiDuan(name);
        entity.setXiuGaiQianZhi(oldValue);
        entity.setXiuGaiHouZhi(newValue);
        super.save(entity);          
      } catch (Exception e) {
        throw new AvensRemoteDatabaseDaoException("insert XtUpdateDataDO failed!");
      }
    }

  }

  private String getStringValue(Object object, Field field) {
    if (object == null) {
      return null;
    }
    String value;
    if (object instanceof Date) {      
      value = DateUtil.formatTime((Date) object);
    } else {
      value = object.toString();
    }
    return value;
  }



}
